import { createRouter, createWebHistory } from "vue-router";
import store from "../store";

// 路由列表
const routes = [
  {
    meta: {
      title: "首页-浮光在线",
    },
    path: "/",
    name: "Home",
    component: () => import("../views/Home.vue"),
  },
  {
    meta: {
      title: "登录-浮光在线",
    },
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  {
    meta: {
      title: "注册-浮光在线",
    },
    path: "/register",
    name: "Register",
    component: () => import("../views/Register.vue"),
  },
  {
    meta: {
      titel: "项目课-浮光在线",
    },
    path: "/project",
    name: "Course",
    component: () => import("../views/Course.vue"),
  },
  {
    meta: {
      title: "课程详情-浮光在线",
      keepAlive: true,
    },
    path: "/project/:id", // :id 为路由参数
    name: "Info",
    component: () => import("../views/Info.vue"),
  },
  {
    meta: {
      title: "购物车",
      keepAlive: true,
    },
    path: "/cart",
    name: "Cart",
    component: () => import("../views/Cart.vue"),
  },
  {
    meta: {
      title: "确认订单",
      keepAlive: true,
    },
    path: "/order",
    name: "Order",
    component: () => import("../views/Order.vue"),
  },
  {
    meta: {
      title: "支付成功",
      keepAlive: true,
    },
    path: "/alipay",
    name: "PaySuccess",
    component: () => import("../views/AliPaySuccess.vue"),
  },
  {
    meta: {
      title: "个人中心-浮光在线",
      keepAlive: true,
    },
    path: "/user",
    name: "User",
    component: () => import("../views/User.vue"),
    children: [
      {
        meta: {
          title: "个人信息-浮光在线",
        },
        path: "",
        name: "UserInfo",
        component: () => import("../components/user/Info.vue"),
      },
      {
        meta: {
          title: "我的订单-浮光在线",
        },
        path: "order",
        name: "UserOrder",
        component: () => import("../components/user/Order.vue"),
      },
      {
        meta: {
          title: "我的课程-浮光在线",
          keepAlive: true,
        },
        path: "course",
        name: "UserCourse",
        component: () => import("../components/user/Course.vue"),
      },
    ],
  },
  {
    meta: {
      title: "个人中心-学习中心",
      keepAlive: true,
      authorization: true,
    },
    path: "/user/study/:course",
    name: "Study",
    component: () => import("../views/Study.vue"),
  },
];

// 路由对象实例化
const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 客户端权限验证写在路由守卫里面
// 服务端的验证，分2块，1块在客户端的axios附带token，另1块在api服务端的视图中调用permission

router.beforeEach((to, from, next) => {
  document.title = to.meta.title;
  // 登录状态验证
  if (to.meta.authorization && !store.getters.getUserInfo) {
    next({ name: "Login" });
  } else {
    next();
  }
});

export default router;
